using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Dynamic;
using System.Linq;
using Avalonia.Threading;
using AvaloniaApplication1.IServices;
using AvaloniaApplication1.IServices.NavigationInterface;
using AvaloniaApplication1.Models;
using AvaloniaApplication1.Models.DTOModel;
using AvaloniaApplication1.Util;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Elasticsearch.Net.Specification.IndicesApi;
using MQTTnet.Internal;
using SukiUI.Dialogs;

namespace AvaloniaApplication1.ViewModels.CardViewModel;

public partial class TopicDisplayViewModel : ObservableObject, IPageLifecycle
{
    /// <summary>
    /// 步骤索引
    /// </summary>
    [ObservableProperty] private int _stepIndex = 0;

    [ObservableProperty] private bool _step1Display = true;
    [ObservableProperty] private bool _step2Display = false;
    [ObservableProperty] private bool _step3Display = false;

    [ObservableProperty] private int _receiveCounter = 0;

    /// <summary>
    /// 设备ID列表
    /// </summary>
    [ObservableProperty] private ObservableCollection<MqttDeviceModel> _deviceIdItems = [];

    [ObservableProperty] private ObservableCollection<string> _deviceIdItemIds = [];

    /// <summary>
    /// 选中的设备ID
    /// </summary>
    [ObservableProperty] private string _selectedDeviceId;

    /// <summary>
    /// 选中的设备Topic
    /// </summary>
    [ObservableProperty] private string _selectedDeviceTopic;

    [ObservableProperty] private ObservableCollection<string> _deviceIdItemTopics = [];

    /// <summary>
    /// 显示的Modbus主题数据
    /// </summary>
    [ObservableProperty] private ObservableCollection<ModbusData> _displayDeviceModbusData = new();

    [ObservableProperty] private ObservableCollection<ExpandoObject> _displayDeviceGenericData;

    /// <summary>
    /// 是否显示Modbus数据
    /// </summary>
    [ObservableProperty] private bool _isModbusDataVisible = false;

    /// <summary>
    /// 是否显示通用数据
    /// </summary>
    [ObservableProperty] private bool _isGenericDataVisible = false;

    /// <summary>
    /// 设备管理器
    /// </summary>
    [ObservableProperty] private IMqttDeviceManager _deviceManager;

    [ObservableProperty] private ISukiDialogManager _dialogManager;

    public IEnumerable<string> Steps { get; } =
        ["First Step", "Second Step", "Third Step"];

    public TopicDisplayViewModel(IMqttDeviceManager deviceManager, ISukiDialogManager dialogManager)
    {
        DeviceManager = deviceManager;
        DialogManager = dialogManager;
        DisplayDeviceModbusData = [];
        DisplayDeviceGenericData = new ObservableCollection<ExpandoObject>();

        var deviceModels = DeviceManager.GetAllDevices();
        foreach (var mqttDeviceModel in deviceModels)
        {
            DeviceIdItems.Add(mqttDeviceModel);
            DeviceIdItemIds.Add(mqttDeviceModel.DeviceId);
            //每个设备的Topic列表
            foreach (var topic in mqttDeviceModel.Topics)
            {
                DeviceIdItemTopics.Add(topic.Topic);
            }
        }
    }


    [RelayCommand]
    public void NextStep()
    {
        if (SelectedDeviceId == null)
        {
            DialogManager.CreateDialog().WithContent("请选择设备").WithActionButton("关闭", _ => { }, true)
                .TryShow();
            return;
        }

        if (Step2Display && SelectedDeviceTopic == null)
        {
            DialogManager.CreateDialog().WithContent("请选择设备Topic").WithActionButton("关闭", _ => { }, true)
                .TryShow();
            return;
        }

        StepIndex++;

        if (StepIndex >= Steps.Count())
        {
            StepIndex = 0;
        }
    }

    partial void OnSelectedDeviceIdChanged(string value)
    {
        DeviceIdItemTopics.Clear();
        //遍历DeviceIdItems设备的Topic列表
        foreach (var mqttDeviceModel in DeviceIdItems)
        {
            if (mqttDeviceModel.DeviceId == value)
            {
                foreach (var topic in mqttDeviceModel.Topics)
                {
                    DeviceIdItemTopics.Add(topic.Topic);
                }
            }
        }
    }

    partial void OnSelectedDeviceTopicChanged(string value)
    {
        // 先移除之前的订阅，避免重复订阅
        DeviceManager.DeviceDataReceived -= DeviceReceivedData;

        if (value != null)
        {
            DeviceManager.DeviceDataReceived += DeviceReceivedData;
            return;
        }
    }

    private void DeviceReceivedData(object? sender, DeviceDataEventArgs e)
    {
        // 根据消息类型决定显示哪种数据
        if (e.MessageData.MessageType == "Modbus" && SelectedDeviceTopic.Contains("modbus"))
        {
            var modbusData = new ModbusData(
                e.MessageData.ParsedData.GetValueOrDefault("DeviceId", "N/A")?.ToString(),
                e.MessageData.ParsedData.GetValueOrDefault("BaudRate", "N/A").ToString(),
                e.MessageData.ParsedData.GetValueOrDefault("Temperature", "N/A").ToString(),
                e.MessageData.ParsedData.GetValueOrDefault("Humidity", "N/A").ToString()
            );

            Dispatcher.UIThread.InvokeAsync(() =>
            {
                IsModbusDataVisible = true;
                IsGenericDataVisible = false;

                DisplayDeviceModbusData.Add(modbusData);
                if (DisplayDeviceModbusData.Count > 10)
                {
                    DisplayDeviceModbusData.RemoveAt(0);
                }
            });
        }
        else if (SelectedDeviceTopic != null && !SelectedDeviceTopic.Contains("modbus"))
        {
            var data = e.MessageData.ParsedData;

            Dispatcher.UIThread.InvokeAsync(() =>
            {
                IsModbusDataVisible = false;
                IsGenericDataVisible = true;
                ReceiveCounter++;
                // 转换为 ExpandoObject 以支持 DataGrid 绑定
                // 动态添加列
                // 修改点 A1：确保列集合与 data.Keys 一致
                // 1) 为当前 data 的键，逐一确保列存在
                // 创建 ExpandoObject
                dynamic expando = new ExpandoObject();
                var expandoDict = (IDictionary<string, object>)expando;
                expandoDict["ReceiveTime"] = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
                expandoDict["ReceiveIndex"] = ReceiveCounter;


                foreach (var kvp in data)
                {
                    expandoDict[kvp.Key] = kvp.Value ?? "N/A";
                }

                DisplayDeviceGenericData.Add(expando);

                if (DisplayDeviceGenericData.Count > 10)
                {
                    DisplayDeviceGenericData.RemoveAt(0);
                }


                AppLogger.Information($"{nameof(TopicDisplayViewModel)}-" +
                                      $"success-add-currentTime-{DateTime.Now} " +
                                      $"current count:{DisplayDeviceGenericData.Count} " +
                                      $"data:{string.Join(", ", expandoDict.Select(kvp => $"{kvp.Key}={kvp.Value}"))}");

                // 3) 控制行数不超过 10 行
                if (DisplayDeviceGenericData.Count > 10)
                {
                    DisplayDeviceGenericData.RemoveAt(0);
                }
            });
        }
    }

    partial void OnStepIndexChanged(int value)
    {
        Step1Display = value switch
        {
            0 => true,
            1 => false,
            2 => false,
            _ => Step1Display
        };
        Step2Display = value switch
        {
            0 => false,
            1 => true,
            2 => false,
            _ => Step2Display
        };
        Step3Display = value switch
        {
            0 => false,
            1 => false,
            2 => true,
            _ => Step3Display
        };
    }

    [RelayCommand]
    public void PreviousStep()
    {
        StepIndex--;

        if (StepIndex == 0)
        {
            //清空主题列表和SelectedDeviceId
            DeviceIdItemTopics.Clear();
            SelectedDeviceId = null;
            SelectedDeviceTopic = null;
        }

        if (StepIndex == 1)
        {
            DisplayDeviceModbusData.Clear();
            SelectedDeviceTopic = null;
        }
    }

    public void OnPageEntering()
    {
        AppLogger.Information($"{nameof(TopicDisplayViewModel)}--" +
                              $"{nameof(OnPageEntering)}-" +
                              $"{nameof(TopicDisplayViewModel)}");
        StepIndex=0;
        SelectedDeviceId = null;
    }

    public void OnPageLeaving()
    {
      
        // 只有当当前有选中的主题时，才记录取消订阅日志
        if (!string.IsNullOrEmpty(SelectedDeviceTopic))
        {
            DeviceManager.DeviceDataReceived -= DeviceReceivedData;
            AppLogger.Information($"{SelectedDeviceTopic} cancel subscribe to {SelectedDeviceTopic} current time:{DateTime.Now}");
        }
        else
        {
            // 如果没有选中的主题，只移除事件订阅（如果已订阅）
            DeviceManager.DeviceDataReceived -= DeviceReceivedData;
           //释放掉此页所有的资源;
           GC.SuppressFinalize(this);
         
        }
    }
 
 
}